package com.example.winner.datepickerdialog;

import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;

import java.util.Calendar;
import java.util.Locale;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    private TextView show=null;
    private Button set=null;
    private int year;
    private int month;
    private int day;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show=(TextView)findViewById(R.id.show);
        set=(Button)findViewById(R.id.set);
        Calendar c=Calendar.getInstance(Locale.CANADA);
        Date mydate=new Date();
        c.setTime(mydate);
        year=c.get(Calendar.YEAR);
        month=c.get(Calendar.MONTH);
        day=c.get(Calendar.DAY_OF_MONTH);
        show.setText("当前日期："+year+"年"+month+"月"+day+"日");
        set.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datepicker=new DatePickerDialog(MainActivity.this,datelistener,year,month,day);
                datepicker.show();
            }
        });
    }
    private DatePickerDialog.OnDateSetListener datelistener=new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int y, int m, int d) {
            Date date=new Date(y-1900,m,d);
            Date current=new Date();
            if(date.getTime()<=current.getTime())
            {
                year=y;
                month=m;
                day=d;
                updateDate();
            }
            else
            {
                Toast.makeText(MainActivity.this,"设置日期无效",Toast.LENGTH_SHORT).show();
            }
        }
        private void updateDate()
        {
            show.setText("当前日期："+year+"年"+month+"月"+day+"日");
        }
    };
}
